/*
 * Created on 2005-5-16
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.haoxi.gateway.connector.impl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Administrator Window - Preferences - Java - Code Style - Code
 *         Templates
 */

public class SGIPDeliverServer extends Thread {
    protected static final Log log = LogFactory.getLog(SGIPDeliverServer.class);

    private int maxConnections;
    private int listenPort;
    private ServerSocket serversocket;
    private SSEventListener listener;
    private int status;
    private static final int ON = 0;
    private static final int OFF = 1;
    public  static int socketcount = 0;

    public SGIPDeliverServer(int aListenPort, int maxConnections,
            SSEventListener listener) {
        // 将状态设为OFF，此时不启动服务
        status = OFF;
        // SP的监听端口号
        this.maxConnections = maxConnections;
        this.listener = listener;
        this.listenPort = aListenPort;
        start();
    }

    public static int getSocketCount() {
        return socketcount;
    }

    public synchronized void beginListen() throws IOException {
        // 如果状态为0表示服务器监听已经启动
        if (status == ON) {
            return;
        }
        try {
            log.debug("Thread: SGIPDeliverServer start !!!");
            log.debug("listenPort=="+listenPort+"maxConnections=="+maxConnections);
            // 启动服务
            serversocket = new ServerSocket(listenPort, maxConnections);
            // 将状态设为已经连接
            status = ON;
            log.debug("Thread: SGIPDeliverServer end !!!");
            // 通知线程启动
            notifyAll();
        } catch (IOException ioex) {
            throw ioex;
        }
    }

    /**
     * 第一遍初始化的时候会将此线程挂起， 只有调度了beginListen方法后才会接受客户端的连接
     */
    public void run() {
        do {
            if (status == ON) {
                try {
                    log.debug("wait socket!!!!");
                    // 如果状态为0，等待连接
                    // 如果建立成功
                    Socket incoming = serversocket.accept();
                    log.debug(" socket accept!!!!");
                    if (status == ON) {
                        // 触发连接事件
                            socketcount++;
                            listener.onConnect(incoming);
                    }
                } catch (Exception ex) {
                    if (status != ON)
                        ;
                }
            } else {
                // 
                synchronized (this) {
                    try {
                        // 将线程挂起
                        wait(10000L);
                    } catch (Exception exception) {
                    }
                }
            }
        } while (true);

    }

}
